<template>
  <div class="chat-container">
    <div class="chat-history" ref="chatHistory">
      <div
        v-for="(message, index) in messages"
        :key="index"
        class="message-container"
        :class="{ 'user-container': message.user }"
      >
        <div class="message-bubble" :class="message.user ? 'user-bubble' : 'ai-bubble'">
          {{ message.text }}
        </div>
      </div>
    </div>

    <div class="input-area">
      <textarea
        v-model="userInput"
        placeholder="请输入您的问题..."
        @keydown.enter.prevent="sendMessage"
      ></textarea>
      <input
        type="file"
        ref="fileInput"
        @change="handleFileUpload"
        style="display: none"
        accept=".txt,.pdf,.doc,.docx,.ppt,.pptx"
      />
      <div class="button-group">
        <button @click="triggerFileUpload" class="upload-button">
          <i class="upload-icon">📎</i>
        </button>
        <button @click="sendMessage" class="send-button">发送</button>
      </div>
    </div>

    <!-- 添加思维导图查看器 -->
    <!-- <XMindViewer
      v-if="showMindMap"
      :url="mindMapUrl"
      :title="mindMapTitle"
      @close="closeMindMap"
    /> -->
  </div>
</template>

<script setup>
import { ref, nextTick, watch, onMounted, onUnmounted } from 'vue';
import { sseConnect, chatWithAI, uploadFile, getHistory } from '@/api/ai';
// import XMindViewer from './XmindViewer.vue';  // 确保已导入

const userInput = ref('');
const messages = ref([]);
// const mindMapUrl = ref('');      // 添加这行
// const mindMapTitle = ref('');    // 添加这行
// const showMindMap = ref(false);  // 添加这行
const chatHistory = ref(null);
const fileInput = ref(null);

const emits = defineEmits(['send']); // 通知父组件

const props = defineProps({
  isLoggedIn: Boolean,
});

let eventSource = null;

// 添加重连相关变量
let retryCount = 0;
const maxRetries = 3;
const retryDelay = 2000; // 初始重试延迟时间（毫秒）

// 监听登录状态变化
watch(() => props.isLoggedIn, (newValue) => {
  if (newValue) {
    initSSEConnection();
  } else {
    closeSSEConnection();
  }
});

// 初始化 SSE 连接
const initSSEConnection = async () => {
  try {
    console.log('开始建立 SSE 连接');
    closeSSEConnection();
    
    try {
      eventSource = sseConnect();
      
      eventSource.onopen = () => {
        console.log('SSE 连接已建立');
        retryCount = 0;
      };
      
      eventSource.onmessage = async (event) => {
        try {
          // console.log('收到SSE消息原始数据:', event.data);
          const response = JSON.parse(event.data);
          // console.log('解析后的消息内容:', response);
          let messageContent = response.body;
          
          // 检查消息内容是否为空
          if (!messageContent || messageContent.trim() === '') {
            console.warn('收到空消息内容，跳过处理');
            return;
          }
          
          // 过滤掉 "SSE连接已建立" 消息
          if (messageContent === 'SSE连接已建立') {
            return;
          }
          
          // 如果是新的AI回复，创建新的消息框
          if (messages.value.length === 0 || messages.value[messages.value.length - 1].user) {
            messages.value.push({
              user: false,
              text: '',
              fullText: '',
              isComplete: false
            });
          }
          
          const currentMessage = messages.value[messages.value.length - 1];
          
          // 将新内容追加到完整文本中，但先检查和处理undefined
          if (messageContent && messageContent !== 'undefined') {
            currentMessage.fullText += messageContent;
            
            // 清理和格式化文本内容
            let cleanedText = currentMessage.fullText
              .replace(/undefined/g, '') // 移除所有undefined字符串
              .replace(/\*\s*\*/g, '')
              .replace(/\*/g, '')
              .replace(/\s+/g, ' ')
              .trim();

            // 处理 ### 标记
            cleanedText = cleanedText
              .split('###')  // 按 ### 分割
              .map(part => part.trim())  // 清理每部分的空白
              .join('\n\n');  // 用换行重新连接

            // 更新显示的文本
            currentMessage.text = cleanedText;
          }

          scrollToBottom();
        } catch (error) {
          console.error('处理SSE消息失败:', error);
        }
      };
      
      eventSource.onerror = (error) => {
        console.error('SSE 连接错误:', error);
        
        if (retryCount < maxRetries) {
          retryCount++;
          const currentDelay = retryDelay * retryCount;
          console.log(`连接断开，${currentDelay / 1000}秒后重试...（${retryCount}/${maxRetries}）`);
          
          setTimeout(() => {
            if (props.isLoggedIn) {
              initSSEConnection();
            }
          }, currentDelay);
        } else {
          console.error('连接失败，请刷新页面重试');
          closeSSEConnection();
        }
      };
    } catch (connectionError) {
      console.error('建立 SSE 连接时发生错误:', connectionError);
      throw connectionError;
    }
  } catch (error) {
    console.error('SSE 连接流程失败:', error);
  }
};

// 关闭 SSE 连接
const closeSSEConnection = () => {
  if (eventSource) {
    console.log('关闭 SSE 连接');
    eventSource.close();
    eventSource = null;
    retryCount = 0; // 主动关闭时重置重试计数
  }
};

// 组件挂载时，如果已登录则建立连接
// 添加获取历史消息的方法
const loadHistoryMessages = async () => {
  try {
    const response = await getHistory();
    if (response.status === 200 && response.data.data) {
      // 将历史消息添加到消息列表中
      messages.value = response.data.data.map(msg => ({
        user: msg.type === 'user',
        text: msg.msg
      }));
      
      // 滚动到底部
      scrollToBottom();
    }
  } catch (error) {
    console.error('获取历史消息失败:', error);
  }
};

// 修改 onMounted 钩子
onMounted(() => {
  if (props.isLoggedIn) {
    initSSEConnection();
    loadHistoryMessages(); // 加载历史消息
  }
});

// 组件卸载时关闭连接
onUnmounted(() => {
  // 确保在关闭连接前完成所有pending的消息处理
  if (eventSource) {
    eventSource.onmessage = null; // 移除消息监听
    eventSource.onerror = null; // 移除错误监听
    closeSSEConnection();
  }
});

// 发送消息方法
const sendMessage = async () => {
  if (!userInput.value.trim()) return;

  if (!props.isLoggedIn) {
    emits('send');
    return;
  }

  const messageText = userInput.value.trim();
  
  messages.value.push({
    user: true,
    text: messageText,
  });

  userInput.value = '';
  scrollToBottom();

  try {
    // 修改发送消息的格式
    const response = await chatWithAI({
      message: messageText,
      userId: localStorage.getItem('userInfo') ? JSON.parse(localStorage.getItem('userInfo')).id : null
    });
    
    if (!response || response.status !== 200) {
      throw new Error('发送失败');
    }
    
    // console.log('消息发送成功，等待 SSE 响应');
  } catch (error) {
    console.error('发送消息失败:', error);
    messages.value.push({
      user: false,
      text: '消息发送失败，请稍后重试'
    });
    scrollToBottom();
  }
};

const triggerFileUpload = () => {
  fileInput.value.click();
};

// 修改 handleFileUpload 函数
const handleFileUpload = async (event) => {
  const file = event.target.files[0];
  if (!file) return;

  const maxSize = 50 * 1024 * 1024; // 50MB
  if (file.size > maxSize) {
    alert('文件大小不能超过 50MB');
    return;
  }

  try {
    messages.value.push({
      user: true,
      text: `正在上传文件: ${file.name}`,
    });

    const formData = new FormData();
    formData.append('file', file);
    
    // 调用上传文件 API
    const response = await uploadFile(formData);

    console.log('文件上传响应:', response)
    
    if (response.status === 200) {
      // 保存materialId到localStorage
      if(response.data.data?.materialId) {
        localStorage.setItem('currentMaterialId', response.data.data.materialId);
      }
      
      // 添加上传成功消息，并将 URL 转换为超链接
      const xmindUrl = response.data.data?.xmindUrl || '链接生成失败';
      const linkText = xmindUrl !== '链接生成失败' ? `思维导图链接：${xmindUrl}` : xmindUrl;
      
      messages.value.push({
        user: false,
        text: `文件 ${file.name} 上传成功！\n我已经为您生成了思维导图，您可以通过以下链接查看：\n${linkText}`,
      });
      
      // 注释掉思维导图查看器相关代码
      /*
      if (response.data.data?.xmindUrl) {
        console.log('思维导图URL:', response.data.data.xmindUrl);
        mindMapUrl.value = response.data.data.xmindUrl;
        mindMapTitle.value = file.name;
        showMindMap.value = true;
      }
      */
      
      console.log('文件上传成功，等待 SSE 返回分析结果');
    } else {
      throw new Error('上传失败');
    }
    
    scrollToBottom();
  } catch (error) {
    console.error('文件上传失败:', error);
    messages.value.push({
      user: false,
      text: '文件上传失败，请稍后重试'
    });
  } finally {
    event.target.value = ''; // 清除文件输入，允许重新选择相同文件
  }
};

// 关闭思维导图查看器
// const closeMindMap = () => {
//   showMindMap.value = false;
// };

const scrollToBottom = () => {
  nextTick(() => {
    if (chatHistory.value) {
      chatHistory.value.scrollTop = chatHistory.value.scrollHeight;
    }
  });
};

const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));
</script>

<style scoped>
.chat-container {
  max-width: 800px;
  margin: 0 auto;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.chat-history {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
}

.message-container {
  margin: 15px 0;
}

.message-bubble {
  --max-bubble-width: min(600px, 70%);
  padding: 12px 18px;
  border-radius: 12px;
  font-size: 14px;
  line-height: 1.5;
  width: fit-content;
  max-width: var(--max-bubble-width);
  min-width: 5px;
  word-break: break-word;
  white-space: pre-wrap;
  overflow-wrap: break-word;
}

.ai-bubble {
  background: white;
  color: #333;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  max-width: min(600px, 65%);
}

.user-bubble {
  background: #007aff;
  color: white;
  margin-left: auto;
  max-width: min(600px, 75%);
}

.input-area {
  padding: 20px;
  display: flex;
  gap: 12px;
  border-top: 1px solid #eee;
}

textarea {
  flex: 1;
  padding: 12px;
  border: 1px solid #ddd;
  border-radius: 8px;
  resize: none;
  min-height: 44px;
  max-height: 150px;
  font-size: 14px;
}

.send-button {
  background: #e8e8e8;
  color: #333;
  border: 1px solid #ccc;
  padding: 0 24px;
  border-radius: 8px;
  cursor: pointer;
  transition: opacity 0.2s, background 0.2s;
}

.send-button:hover {
  background: #d8d8d8;
}

.button-group {
  display: flex;
  gap: 8px;
}

.upload-button {
  background: #e8e8e8;
  color: #333;
  border: 1px solid #ccc;
  width: 44px;
  height: 70px;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s;
  display: flex;
  align-items: center;
  justify-content: center;
}

.upload-button:hover {
  background: #d8d8d8;
}

.upload-icon {
  font-size: 20px;
  line-height: 1;
}

.send-button {
  min-width: 80px;
}

/* 添加遮罩样式 */
.mindmap-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  z-index: 999;
}

/* 美化滚动条 */
.chat-history::-webkit-scrollbar {
  width: 3px; /* 滚动条宽度 */
}

.chat-history::-webkit-scrollbar-track {
  background: #f1f1f1; /* 滚动条轨道颜色 */
  border-radius: 10px; /* 圆角 */
}

.chat-history::-webkit-scrollbar-thumb {
  background: #b3b1b1; /* 滚动条颜色 */
  border-radius: 10px; /* 圆角 */
}

.chat-history::-webkit-scrollbar-thumb:hover {
  background: #555; /* 滚动条悬停颜色 */
}
</style>